const {
  Service,
} = require('uni-cloud-router')
const {
  TaskType,
} = require('../constants/const')
const {
  generateToken,
} = require('../utils/Auth')
const ResponseUtil = require('../utils/Response')

async function fetchOpenId(code) {
  const info = await this.db.collection('app-info').get()
  const {
    appId,
    appSecret,
  } = info.data[0] || {}
  // 调用微信接口获取openid
  const url
    = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`
  // 发起网络请求
  const {
    data: {
      openid,
    },
  } = await this.curl(url, {
    method: 'GET',
    dataType: 'json',
  })

  return openid
}

module.exports = class RegisterService extends Service {
  async register(data) {
    const {
      avatarUrl,
      nickName,
      childName,
      code,
    } = data
    const openid = await fetchOpenId.call(this, code)

    const userInfo = await this.db.collection('user').where({
      openid,
    }).get()

    const token = generateToken(openid)

    if (userInfo.data.length) {
      // await uniCloud.deleteFile({
      //   fileList: [userInfo.data[0].avatarUrl],
      // })
      return ResponseUtil.success(token)
    }
    const transaction = await this.db.startTransaction()

    try {
      await transaction.collection('user').add({
        openid,
        avatarUrl,
        nickName,
        createdAt: new Date(),
      })

      await transaction.collection('child').add({
        parent: openid,
        name: childName,
        score: 0,
      })

      await transaction.commit()

      return ResponseUtil.success(token)
    }
    catch (error) {
      console.error(error)
      transaction.rollback()
      return ResponseUtil.error('注册失败')
    }
  }

  async login(data) {
    const {
      code,
    } = data

    const openid = await fetchOpenId.call(this, code)
    const userInfo = await this.db.collection('user').where({
      openid,
    }).get()

    const token = generateToken(openid)

    if (userInfo.data.length) {
      return ResponseUtil.success(token)
    }
    else {
      return ResponseUtil.error('用户不存在', 404)
    }
  }
}
